package com.atguigu.tingshu.user.strategy.impl;

import cn.hutool.core.collection.CollUtil;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.strategy.PaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component("1002")
public class TrackPaidRecordStrategy implements PaidRecordStrategy {
    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;
    @Override
    public void handlerPaidRecord(UserPaidRecordVo userPaidRecordVo) {
        //2.1根据订单编号判断是否已经购买过该声音
        Long count = userPaidTrackMapper.selectCount(new LambdaQueryWrapper<UserPaidTrack>()
                .eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo())
                .select(UserPaidTrack::getId));
        if (count > 0){
            return;
        }
        List<Long> trackIdList = userPaidRecordVo.getItemIdList();
        if (CollUtil.isNotEmpty(trackIdList)){
            //根据声音ID查询声音信息
            TrackInfo trackInfo = albumFeignClient.getTrackInfo(trackIdList.get(0)).getData();
//            List<UserPaidTrack> userPaidTrackList = trackIdList
//                    .stream()
//                    .map(trackId -> {
//                        UserPaidTrack userPaidTrack = new UserPaidTrack();
//                        userPaidTrack.setUserId(userPaidRecordVo.getUserId());
//                        userPaidTrack.setTrackId(trackId);
//                        userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
//                        userPaidTrack.setAlbumId(trackInfo.getAlbumId());
//                        return userPaidTrack;
//                    }).collect(Collectors.toList());
//            userPaidTrackService.saveBatch(userPaidTrackList);
            Long albumId = trackInfo.getAlbumId();
            for (Long trackId : trackIdList) {
                UserPaidTrack userPaidTrack = new UserPaidTrack();
                userPaidTrack.setAlbumId(albumId);
                userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
                userPaidTrack.setTrackId(trackId);
                userPaidTrack.setUserId(userPaidRecordVo.getUserId());
                userPaidTrackMapper.insert(userPaidTrack);
            }
        }

    }
}
